<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2017/12/15
 * Time: 10:58
 */

namespace Biz\service;

use Biz\cache\Shop as cShop;
use Biz\cache\ShopServiceStatement as cShopServiceStatement;
use Biz\model\OperateLog as mOperateLog;
use Biz\model\ShopAnnounce as mShopAnnounce;
use Biz\model\ShopAuth as mShopAuth;
use Biz\model\ShopBankInfo as mShopBankInfo;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\model\ShopCommissionRate as mShopCommissionRate;
use Biz\model\ShopCompanyInfo as mShopCompanyInfo;
use Biz\model\ShopContactInfo as mShopContactInfo;
use Biz\model\ShopIdentifyImage as mShopIdentifyImage;
use Biz\model\ShopPersonalInfo as mShopPersonalInfo;
use Biz\model\ShopSecurityDeposit as mShopSecurityDeposit;
use Biz\model\ShopServiceStatement as mShopServiceStatement;
use Biz\model\ShopSwitch as mShopSwitch;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\module\Classes\adm\ShopSearch as clsAdmShopSearch;
use Biz\module\Classes\ShopStatus as clsShopStatus;
use Biz\module\Packages\CustomerService\SmallEnergy as csSmallEnergy;
use Biz\pockets\constInterface\CategoryExtendInfo;
use Biz\service\activity\ActivityRegisterInfo as sActivityRegisterInfo;
use Biz\service\settlement\Settlement;
use Biz\service\ShopSecurityDeposit as sShopSecurityDeposit;
use Biz\service\trade\ShopCourier as sShopCourier;
use Doraemon\model\Category as mCategory;
use Doraemon\model\Member as mMember;
use Doraemon\model\Phone;
use Doraemon\model\Phone as mPhone;
use Doraemon\model\Qq;
use Doraemon\model\Sina;
use Doraemon\model\Weixin;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\User as sUser;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log as tLog;
use hhz\constant\basic\findPhoneScene;

class ShopInfo implements CategoryExtendInfo
{
    const SHOP_PHONE_DECRYPT_MIRROR = 'magic_mirror_decrypt_shop_checkin';
    /**
     * @deprecated
     */
    public static function mgtSignupCompanyInfo($uid, $data)
    {
        try {
            $info = mShopBasicInfo::getInfo($uid);

            if ($info['type'] != mShopBasicInfo::TYPE_COMPANY) {
                throw new \Exception('抱歉，请从正确渠道提交');
            }

            mShopCompanyInfo::action(function () use ($uid, $data) {

                mShopCompanyInfo::createOrEdit($uid, [
                    'name' => isset($data['name']) ? $data['name'] : '',
                    'social_credit_code' => isset($data['social_credit_code']) ? $data['social_credit_code'] : '',
                    'legal_person' => isset($data['legal_person']) ? $data['legal_person'] : '',
                    'legal_person_id_number' => isset($data['legal_person_id_number']) ? $data['legal_person_id_number'] : '',
                    'telephone' => isset($data['telephone']) ? $data['telephone'] : '',
                ], 'signup');


                mShopContactInfo::createOrEdit($uid, [
                    'name' => isset($data['contact']) ? $data['contact'] : '',
                    'position' => isset($data['position']) ? $data['position'] : '',
                    'mobile' => isset($data['mobile']) ? $data['mobile'] : '',
                    'master' => 1
                ], 'signup');

            });


        } catch (\Exception $e) {
            tLog::warning("保存商家企业信息时出错", [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);


            throw $e;
        }

    }

    public static function mgtSignupPersonalInfo($uid, $data)
    {
        try {

            $info = mShopBasicInfo::getInfo($uid);

            if ($info['type'] != mShopBasicInfo::TYPE_PERSONAL) {
                throw new \Exception('抱歉，请从正确渠道提交');
            }

            mShopPersonalInfo::action(function () use ($uid, $data) {

                mShopPersonalInfo::createOrEdit($uid, $data, 'signup');

                $phone = Phone::getDecryptPhoneByUid($uid, findPhoneScene::SHOP_INFO_PHONE);
                if ($phone) {
                    mShopContactInfo::createOrEdit($uid, [
                        'name' => $data['realname'],
                        'position' => '店铺所有人',
                        'mobile' => $phone,
                        'master' => 1
                    ], 'signup');
                }

            });


        } catch (\Exception $e) {
            tLog::warning("保存个人商家信息出错", [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function mgtSignupBankInfo($uid, $data)
    {
        try {

            mShopBankInfo::createOrEdit($uid, $data, 'signup');

            clsShopStatus::mgtSubmitWaitAudit($uid);

        } catch (\Exception $e) {

            tLog::warning("保存银行账号信息出错", [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function mgtSaveAnnounce($shopId, $announce)
    {
        $result = mShopAnnounce::action(function () use ($shopId, $announce) {
            mShopAnnounce::update(['status' => mShopAnnounce::STATUS_DISABLED], [
                'shop_id' => $shopId
            ]);
            if ($announce) {
                mShopAnnounce::insertData($shopId, $announce);
            }
            return true;
        });
        return $result;
    }

    public static function mgtGetAnnounce($shopId)
    {
        $announceId = mShopAnnounce::getAnnounce($shopId);
        if ($announceId) {
            $announceUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $announceId, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return [
                'announce' => $announceId,
                'announce_url' => $announceUrl
            ];
        }
        return [];
    }

    public static function mgtSignupIdentifyImage($uid, $data)
    {
        try {

            mShopIdentifyImage::createOrEdit($uid, $data, 'signup');

        } catch (\Exception $e) {

            tLog::warning("保存商家图片出错", [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);


            throw $e;
        }
    }

    public static function checkShopSignupStatus($uid)
    {

        $check = mShopBasicInfo::checkShopSignupStatus($uid);
        return $check;
    }

    public static function mgtSignupSelectAccount($uid, $type)
    {
        try {

            //查询该用户的基本信息
            $member = mMember::getUserInfo($uid);

            if (empty($member)) {
                throw new \Exception('账户状态不正确');
            }

            //判断该账户是否存在
            $check = mShopBasicInfo::checkExists($uid);

            if ($check) {
                throw new \Exception('账户已存在，不可重新申请');
            }

            mShopBasicInfo::action(function () use ($uid, $type, $member) {

                $agreementStatus = 1;
                if (in_array($uid, [
                    2541904,
                    1048440,
                    257937,
                    1255620,
                    54649,
                    177392,
                    23300,
                    1663553,
                    492844,
                    94238,
                    3791612,
                    13199,
                    22219,
                    1976237,
                    1369714,
                    94850,
                    986344
                ])) {
                    $agreementStatus = 0;
                }

                //初始化基本信息
                mShopBasicInfo::createOrEdit($uid, [
                    'type' => $type,
                    'name' => $member['nick'],
                    'intro' => '还没有介绍哦，请帮忙填写吧',
                    'status' => mShopBasicInfo::STATUS_NORMAL,
                    'agreement_status' => $agreementStatus,
                ], 'signup');

                //初始化保证金信息
                mShopSecurityDeposit::mgtInitAccountData($uid);
            });

        } catch (\Exception $e) {
            tLog::warning('用户选择注册账户类型错误', [
                'uid' => $uid,
                'type' => $type,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);


            throw $e;
        }
    }

    public static function getShopInfoList($shopIds, $from = 'app')
    {
        if ($from == 'app') {
            list($cacheData, $noCacheKeys) = cShop::mGetItems($shopIds);
            if ($noCacheKeys) {
                $shopInfos = mShopBasicInfo::getInfoList($shopIds, $from);
                $shopUsers = sUser::getUsers($shopIds);
                foreach ($shopInfos as $uid => $shopInfo) {
                    if ($shopInfo['status'] != mShopBasicInfo::STATUS_OPENED) {
                        $smallEnergyInfo = ['pre_sale_reception_group_id' => csSmallEnergy::GROUP_ID];
                    } else {
                        $smallEnergyInfo = csSmallEnergy::getSmallEnergyInfoByShopId($uid,
                            ['pre_sale_reception_group_id']);
                    }
                    $shopInfos[$uid]['small_energy'] = $smallEnergyInfo;
                    $shopInfos[$uid]['shop_imgurl'] = isset($shopUsers[$uid]) ? $shopUsers[$uid]['avatar'] : '';
                    $shopInfos[$uid]['shop_imgurl_small'] = isset($shopUsers[$uid]) ? $shopUsers[$uid]['avatar_small'] : '';
                }
                cShop::mSetItems($shopInfos);
                return $cacheData + $shopInfos;
            } else {
                return $cacheData;
            }
        } else {
            $list = mShopBasicInfo::getInfoList($shopIds, $from);
            $shopUsers = sUser::getUsers($shopIds);
            foreach ($list as $uid => &$shopInfo) {
                $shopInfo['shop_imgurl'] = isset($shopUsers[$uid]) ? $shopUsers[$uid]['avatar'] : '';
                $shopInfo['shop_imgurl_small'] = isset($shopUsers[$uid]) ? $shopUsers[$uid]['avatar_small'] : '';
            }
            return $list;
        }
    }

    public static function getShopInfo($uid, $dataCate = ['info', 'bank', 'bind', 'user'], $from = '')
    {
        $data = mShopBasicInfo::getInfo($uid, $from);

        if (empty($dataCate)) {
            return $data;
        }

        foreach ($dataCate as $tag) {
            if ($tag == 'bank') {

                $data['bank'] = mShopBankInfo::getInfo($uid);
            } elseif ($tag == 'contactInfo') {

                $data['contactInfo'] = mShopContactInfo::getAllContactInfo($uid);
            } elseif ($tag == 'info' && $data['type'] == mShopBasicInfo::TYPE_COMPANY) {

                $data['info'] = mShopCompanyInfo::getInfo($uid);
            } elseif ($tag == 'info' && $data['type'] == mShopBasicInfo::TYPE_PERSONAL) {

                $data['info'] = mShopPersonalInfo::getInfo($uid);
            } elseif ($tag == 'identifyImageList') {
                $data['identifyImageList'] = mShopIdentifyImage::getImgList($uid, $data['type'],
                    ['basic', 'other', 'bank']);
            } elseif ($tag == 'auth') {
                $authInfo = mShopAuth::getAuthInfoByUid($uid);
                $data['email'] = $authInfo['email'];
            } elseif ($tag == 'bind') {
                $sinaInfo = Sina::getInfoByUid($uid);
                $weixinInfo = Weixin::getInfoByUid($uid);
                $qqInfo = Qq::getInfoByUid($uid);
                $phone = Phone::getDecryptPhoneByUid($uid, findPhoneScene::SHOP_INFO_PHONE);
                $data['bind']['phone'] = $phone;
                $data['bind']['bind_phone'] = $phone ? 1 : 0;
                $data['bind']['bind_sina'] = $sinaInfo ? 1 : 0;
                $data['bind']['bind_weixin'] = $weixinInfo ? 1 : 0;
                $data['bind']['bind_qq'] = $qqInfo ? 1 : 0;
                if (isset($data['user'])) {
                    $data['user'] = array_merge($data['user'], $data['bind']);
                    unset($data['bind']);
                }
            } elseif ($tag == 'user') {
                $shopUser = sUser::getUser($uid);

                $data['shop_imgurl'] = $shopUser['avatar'];
                $data['shop_imgurl_small'] = $shopUser['avatar_small'];

                $data['user'] = $shopUser;
                if (isset($data['bind'])) {
                    $data['user'] = array_merge($data['user'], $data['bind']);
                    unset($data['bind']);
                }
            }
        }

        return $data;
    }

    public static function getShopIdentifyImageList($uid, $shopType, $cate = ['basic'])
    {
        $res = mShopIdentifyImage::getImgList($uid, $shopType, $cate);

        return $res;
    }


    public static function mgtAddContactInfo($uid, $data, $scenes)
    {
        try {
            mShopContactInfo::createOrEdit($uid, $data, $scenes);

        } catch (\Exception $e) {
            tLog::warning('添加联系人信息出错', [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function mgtModifyContactInfo($uid, $data, $scenes)
    {
        try {

            if (count($data) == 0) {
                throw new \Exception('请至少保存一个联系人信息');
            }

            $contactList = mShopContactInfo::getList($uid);
            $contactList = array_column($contactList, null, 'id');

            $activeList = [];
            $activeIdList = [];

            //整理数据
            foreach ($data as $value) {
                if (isset($value['id']) && $value['id'] > 0) {
                    $activeList[$value['id']] = $value;
                } else {
                    $result = mShopContactInfo::createOrEdit($uid, $value, 'insert');

                    if (isset($result['last_id'])) {
                        $activeIdList[] = $result['last_id'];
                    }
                }
            }


            //把此次没有提交更新的旧数据剔除
            foreach ($contactList as $id => $contact) {
                if (!isset($activeList[$id])) {
                    mShopContactInfo::forceDelById($id);
                } else {
                    mShopContactInfo::createOrEdit($uid, $activeList[$id], 'modify');

                    array_unshift($activeIdList, $id);
                }
            }


            //判断是否还有master，如果没有则新增一个master
            $masterInfo = mShopContactInfo::getMasterInfo($uid);

            if (!empty($masterInfo)) {
                return true;
            }

            if (isset($activeIdList[0])) {
                mShopContactInfo::setMaster($activeIdList[0]);

            }

            return true;


        } catch (\Exception $e) {
            tLog::warning('全量操作联系人信息失败', [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function delContactInfo($shopId, $id)
    {

        try {
            mShopContactInfo::delById($shopId, $id);


        } catch (\Exception $e) {
            tLog::warning('管理员删除联系人信息出错',
                ['id' => $id, 'e_msg' => $e->getMessage(), 'e_file' => $e->getFile(), 'e_line' => $e->getLine()]);

            throw $e;
        }
    }

    public static function updateShopInfo($uid, $data)
    {
        try {
            mShopBasicInfo::createOrEdit($uid, $data, 'update');

        } catch (\Exception $e) {

            tLog::warning('更新商家基本信息出现异常', [
                'uid' => $uid,
                'data' => $data,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }


    public static function admSearchShopList($params, $limit)
    {

        $search = new clsAdmShopSearch($params, $limit);

        return [
            'list' => $search->getList(),
            'total' => $search->getCount()
        ];


    }


    public static function admChangeShopStatus($uid, $oldStatus, $action, $remark, $adminUid = 0)
    {

        try {
            $info = mShopBasicInfo::getInfo($uid);

            if ($info['status'] != $oldStatus) {
                throw new \Exception('提交失败');
            }

            clsShopStatus::checkAdminAction($oldStatus, $action);

            call_user_func_array('Biz\module\Classes\ShopStatus::' . $action, [
                $uid,
                $info['type'],
                $remark,
                $oldStatus,
                $adminUid,
            ]);


        } catch (\Exception $e) {
            tLog::warning('管理员修改商家状态失败', [
                'uid' => $uid,
                'old_status' => $oldStatus,
                'action' => $action,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }

    }

    public static function admCompleteShopApply(
        $uid,
        $oldStatus,
        $action,
        $adminUid,
        $amount,
        $definedRatio,
        $categoryRatio
    )
    {

        try {
            $info = mShopBasicInfo::getInfo($uid);

            if ($info['status'] != $oldStatus) {
                throw new \Exception('提交失败');
            }

            clsShopStatus::checkAdminAction($oldStatus, $action);

            call_user_func_array('Biz\module\Classes\ShopStatus::' . $action, [
                $uid,
                $adminUid,
                $amount,
                $definedRatio,
                $categoryRatio
            ]);

        } catch (\Exception $e) {
            tLog::warning('管理员修改商家状态失败', [
                'uid' => $uid,
                'old_status' => $oldStatus,
                'action' => $action,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }

    }

    public static function mgtGetCouriers($shopId)
    {
        $courierList = sShopCourier::getCourierFileList();

        $isSelfShop = mShopBasicInfo::checkIsSelfOperated($shopId);

        if (!$isSelfShop) {
            $courierList = array_filter($courierList, function ($v) {
                if ($v['courier_id'] == mShopCourier::SELF_LIFTING_ID) {
                    return false;
                }
                return true;
            });
        }

        return array_values($courierList);
    }

    public static function mgtSignupFeedBack($shopId)
    {
        $result = [
            'status' => -1,
        ];
        $info = self::getShopInfo($shopId, ['info', 'auth']);
        if ($info['status'] == mShopBasicInfo::STATUS_WAIT_AUDIT) {

            $result['status'] = mShopBasicInfo::STATUS_WAIT_AUDIT;

        } elseif ($info['status'] == mShopBasicInfo::STATUS_REJECT) {

            $result['status'] = mShopBasicInfo::STATUS_REJECT;
            $result['reason'] = $info['info']['remark'];

        } elseif ($info['status'] == mShopBasicInfo::STATUS_WAIT_PAY_DEPOSIT) {

            $result['status'] = mShopBasicInfo::STATUS_WAIT_PAY_DEPOSIT;

            $depositInfo = sShopSecurityDeposit::getDepositInfo($shopId);

            $result['is_push_adm'] = 0;
            $result['deposit_amount'] = 0;

            if (!empty($depositInfo)) {
                if ($depositInfo['status'] == mShopSecurityDeposit::STATUS_WAIT_CONFIRM) {
                    $result['is_push_adm'] = 1;
                }
                $result['deposit_amount'] = $depositInfo['amount'];
            }


        } else {
            if ($info['status'] == mShopBasicInfo::STATUS_FROZEN) {
                $logInfo = mOperateLog::select('*', [
                    'AND' => [
                        'uid' => $shopId,
                        'type' => mOperateLog::TYPE_SHOP_ADM_CONFIRMED_SHOP_FROZEN
                    ],
                    'ORDER' => ['addtime' => 'DESC'],
                    'LIMIT' => [0, 1]
                ]);
                if ($logInfo) {
                    $logInfo = array_shift($logInfo);
                    $frozenReason = '';
                    if ($logInfo['foreign_id'] == mShopBasicInfo::FROZEN_REASON_CLOSE) {
                        $frozenReason = sprintf('因申请关店，自%s起，店铺开始冻结，在此期间所有商品维持下架状态，已有订单依然可以正常处理。当所有订单、货款和保证金处理完毕之后，店铺即可关闭。'
                            , date('Y年m月d日', strtotime($logInfo['addtime'])));
                    } else {
                        if ($logInfo['foreign_id'] == mShopBasicInfo::FROZEN_REASON_GENERAL) {
                            $frozenReason = sprintf('因【一般违规】扣分累积达到48分 ，根据《商家管理处罚规则》，自%s起，店铺将冻结1个月，在此期间所有商品维持下架状态，已有订单依然可以正常处理。当违规处罚届满，且经好好住核查后，店铺可恢复正常状态。'
                                , date('Y年m月d日', strtotime($logInfo['addtime'])));
                        } else {
                            if ($logInfo['foreign_id'] == mShopBasicInfo::FROZEN_REASON_SERIOUS) {
                                $frozenReason = sprintf('因【严重违规】扣分累积达到36分 ，根据《商家管理处罚规则》，自%s起，店铺将冻结21天，在此期间所有商品维持下架状态，已有订单依然可以正常处理。当违规处罚届满，且经好好住核查后，店铺可恢复正常状态。'
                                    , date('Y年m月d日', strtotime($logInfo['addtime'])));
                            }
                        }
                    }
                    $result['status'] = $info['status'];
                    $result['shop_frozen'] = $frozenReason;
                }
            } else {
                if ($info['status'] == mShopBasicInfo::STATUS_OPENED) {
                    $result['status'] = mShopBasicInfo::STATUS_OPENED;
                    $str = '%s账单已出，请尽快确认以免影响货款结算';
                    $list = Settlement::mgtGetUnConfirmedBills($shopId);
                    $unConfirmed_bills = [];
                    if ($list) {
                        foreach ($list as $row) {
                            $unConfirmed_bills[] = sprintf($str, date('Y年m月', strtotime($row['bill_date'])));
                        }
                    }
                    $result['unConfirmed_bills'] = $unConfirmed_bills;
                    $logInfo = mOperateLog::select('*', [
                        'AND' => [
                            'uid' => $shopId,
                            'type' => mOperateLog::TYPE_SHOP_ADM_CANCEL_SHOP_FROZEN,
                            'addtime[<]' => date('Y-m-d', strtotime('+7 days'))
                        ],
                        'ORDER' => ['addtime' => 'DESC'],
                        'LIMIT' => [0, 1]
                    ]);
                    if ($logInfo) {
                        $logInfo = array_shift($logInfo);
                        $result['shop_frozen'] = '店铺的违规处罚届满，且通过了好好住的核查，即日起店铺恢复正常经营，请尽快上架商品';
                    }
                }

                //报名活动通知
                $notiyRes = sActivityRegisterInfo::mgtGetRegisterNotifyForShop($shopId);
                $result ['activity_register_info'] = $notiyRes['activity_register_info'];
                $result ['activity_register_goods'] = $notiyRes['activity_register_goods'];
            }
        }

        $result['email'] = $info['email'];

        return $result;

    }

    public static function setShopNick($uid)
    {
        if ($user = mMember::getUserInfo($uid)) {
            $info = mShopBasicInfo::getInfo($uid);

            if ($info) {
                $ret = mShopBasicInfo::updateByField(['name' => $user['nick']], ['uid' => $uid]);

                if ($ret == 0) {
                    tLog::queue_shopNick_error('店铺昵称同步失败',
                        ['uid' => $uid, 'old_nick' => $info['name'], 'new_nick' => $user['nick']]);
                    return false;
                }

                tLog::queue_shopNickSuccess_info('异步更新店铺昵称成功',
                    ['uid' => $uid, 'old_nick' => $info['name'], 'new_nick' => $user['nick']]);

                return true;

            } else {
                tLog::queue_shopNick_error('该用户不是商家', ['uid' => $uid, 'nick' => $user['nick']]);
            }
        }
    }

    public static function is_show_hotgoods($uid)
    {
        return mShopSwitch::is_show_hotGoods($uid);
    }

    public static function admShopServiceStatement($shopIds)
    {
        list($cacheData, $nocacheKeys) = cShopServiceStatement::pHGetAllItems($shopIds);
        foreach ($cacheData as $shopId => $cacheDatum) {
            unset($cacheData[$shopId][0]);
        }
        if (!$nocacheKeys) {
            return $cacheData;
        }
        $shopIds = $nocacheKeys;
        $Commissions = mShopCommissionRate::getRatioList($shopIds);
        $secondCateIds = array_column($Commissions, 'category_id');
        $secondCateInfos = mCategory::selectCategorys($secondCateIds);
        $shopServiceStatement = mShopServiceStatement::getList($shopIds);
        $serviceStatementsBasedCateIds = self::SERVICE_STATEMENT_BASEED_CATE_ID;
        $results = [];
        foreach ($Commissions as $commission) {
            $results[$commission['shop_id']][0][0] = ['id' => 0, 'is_selected' => 0];
            foreach ($secondCateInfos as $secondCateInfo) {
                if (
                    $commission['category_id'] == $secondCateInfo['id'] &&
                    in_array($secondCateInfo['father_id'], array_keys($serviceStatementsBasedCateIds)) &&
                    !isset($results[$commission['shop_id']][$secondCateInfo['father_id']])
                ) {
                    foreach ($serviceStatementsBasedCateIds as $k => $serviceStatementsBasedCateId) {
                        if ($k == $secondCateInfo['father_id']) {
                            foreach ($serviceStatementsBasedCateId as $id => $desc) {
                                $results[$commission['shop_id']][$secondCateInfo['father_id']][] = ['id' => $id, 'is_selected' => 0];
                                if (isset($shopServiceStatement[$commission['shop_id']][$secondCateInfo['father_id']])) {
                                    foreach ($results[$commission['shop_id']][$secondCateInfo['father_id']] as &$item) {
                                        if (in_array($item['id'], $shopServiceStatement[$commission['shop_id']][$secondCateInfo['father_id']]['service_statement']))
                                            $item['is_selected'] = 1;
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
        }
        cShopServiceStatement::pHMSetItems($results);
        foreach ($results as $shopId => $result) {
            unset($results[$shopId][0]);
        }

        return $results + $cacheData;

    }


}